package hz.mobileproject.pda.ui.frgment.thrid;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.CleanUtils;
import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;

import org.json.JSONException;
import org.json.JSONObject;

import cn.carbs.android.avatarimageview.library.AvatarImageView;
import hz.mobileproject.pda.R;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.network.OkGoUpdateHttpUtil;
import hz.mobileproject.pda.ui.activity.LoginActivity;
import hz.mobileproject.pda.ui.activity.work.CallRecordActivity;
import hz.mobileproject.pda.ui.base.BaseBackFragment;
import hz.mobileproject.pda.utils.DataCleanManager;
import hz.mobileproject.pda.utils.SettingFileUtil;


/**
 * Created by YoKeyword on 16/6/30.
 */
public class MeFragment extends BaseBackFragment {
    private static final String ARG_MSG = "arg_msg";
    private AvatarImageView item_avatar;
    private Toolbar mToolbar;
    private TextView departName;
    private TextView policeCode;
    private String police_code;
    private String police_name;
    private String department_name;
    private LinearLayout ll_exit;
    private LinearLayout auto_line;
    private LinearLayout ll_cleanCache;
    //版本信息
    private TextView tv_versionName;

    private LinearLayout re_erwei; //版本升级
    private Gson mGson;
    private String mUpdateUrl = Constance.BASE_URL+"/" +Constance.PROJECT_NAME + "/upgrade/downloadApp";


    public static MeFragment newInstance( ) {

        Bundle args = new Bundle();
        MeFragment fragment = new MeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGson = new Gson();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.wechat_fragment_tab_third, container, false);
        initView(view);
        return attachToSwipeBack(view);
    }

    private void initView(View view) {
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        departName = (TextView) view.findViewById(R.id.departName);
        policeCode = (TextView) view.findViewById(R.id.police_code);
        ll_exit = (LinearLayout)view.findViewById(R.id.ll_exit);
        ll_cleanCache =(LinearLayout)view.findViewById(R.id.re_cleanCache);
        auto_line=(LinearLayout)view.findViewById(R.id.re_erweima);//清点记录
        mToolbar.setTitle("我");
        initToolbarNav(mToolbar);
        item_avatar= (AvatarImageView)view.findViewById(R.id.item_avatar);
        tv_versionName = (TextView) view.findViewById(R.id.tv_versionName);
        re_erwei = (LinearLayout) view.findViewById(R.id.re_erwei);

        tv_versionName.setText(SettingFileUtil.getProperties("version"));


        SPUtils spUtils = SPUtils.getInstance("app_login");
        police_code=  spUtils.getString("police_code");
        police_name =spUtils.getString("police_name");
        department_name= spUtils.getString("department_name");

        policeCode.setText(police_code);
        departName.setText(department_name);
        item_avatar.setTextAndColorSeed(police_name,police_name);//“安卓”字样作为产生backgroundcolor的seed

        ll_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent it = new Intent(getActivity(), LoginActivity.class);
                startActivity(it);
                getActivity().finish();

            }
        });


        auto_line.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("auto_line","auto_line");
//                DotTimeLineActivity.launch(getActivity());
                startActivity(new Intent(getContext(), CallRecordActivity.class));
            }
        });

        ll_cleanCache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
                            .setTitle("提示")
                            .setMessage("缓存大小为"+DataCleanManager.getCacheSize(
                                    getContext().getCacheDir()
                            )+",确认清除缓存？")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            })
                            .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
//                                DataCleanManager.cleanInternalCache(getContext().getApplicationContext());
                                    CleanUtils.cleanInternalCache();
                                }
                            });
                    builder.create().show();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        re_erwei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    new UpdateAppManager
                            .Builder()
                            //必须设置，当前Activity
                            .setActivity((Activity) getContext())
                            //必须设置，实现httpManager接口的对象
                            .setHttpManager(new OkGoUpdateHttpUtil())
                            //必须设置，更新地址
                            .setUpdateUrl(mUpdateUrl)

                            //以下设置，都是可选
                            //设置请求方式，默认get
                            .setPost(false)
                            //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
//                                    .setParams(params)
                            //设置点击升级后，消失对话框，默认点击升级后，对话框显示下载进度
                            .hideDialogOnDownloading(false)
                            //设置头部，不设置显示默认的图片，设置图片后自动识别主色调，然后为按钮，进度条设置颜色
//                                    .setTopPic(R.mipmap.top_8)
                            //为按钮，进度条设置颜色，默认从顶部图片自动识别。
                            //.setThemeColor(ColorUtil.getRandomColor())
                            //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
//                                    .setTargetPath(path)
                            //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
                            //.setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                            //不显示通知栏进度条
                            .dismissNotificationProgress()
                            //是否忽略版本
                            //.showIgnoreVersion()

                            .build()
                            //检测是否有新版本
                            .checkNewApp(new UpdateCallback() {
                                /**
                                 * 解析json,自定义协议
                                 *
                                 * @param json 服务器返回的json
                                 * @return UpdateAppBean
                                 */
                                @Override
                                protected UpdateAppBean parseJson(String json) {
                                    UpdateAppBean updateAppBean = new UpdateAppBean();
                                    try {
                                        JSONObject jsonObject = new JSONObject(json);
                                        updateAppBean
                                                //（必须）是否更新Yes,No
                                                .setUpdate(jsonObject.optString("update"))
                                                //（必须）新版本号，
                                                .setNewVersion(jsonObject.optString("new_version"))
                                                //（必须）下载地址
                                                .setApkFileUrl(jsonObject.optString("apk_file_url"))
                                                //（必须）更新内容
                                                .setUpdateLog(jsonObject.optString("update_log"))
                                                //大小，不设置不显示大小，可以不设置
                                                .setTargetSize(jsonObject.optString("target_size"))
                                                //是否强制更新，可以不设置
                                                .setConstraint(false)
                                                //设置md5，可以不设置
                                                .setNewMd5(jsonObject.optString("new_md5"));
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    return updateAppBean;
                                }

                                /**
                                 * 网络请求之前
                                 */
                                @Override
                                public void onBefore() {
//                                            CProgressDialogUtils.showProgressDialog(JavaActivity.this);
                                }

                                /**
                                 * 网路请求之后
                                 */
                                @Override
                                public void onAfter() {
//                                            CProgressDialogUtils.cancelProgressDialog(JavaActivity.this);
                                }

                                /**
                                 * 没有新版本
                                 */
                                @Override
                                public void noNewApp() {
                                    Toast.makeText(getContext(), "没有新版本", Toast.LENGTH_SHORT).show();
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }
//    private void doLogout() {
//        // 发出退出登陆请求包（Android系统要求必须要在独立的线程中发送哦）
//        new AsyncTask<Object, Integer, Integer>(){
//            @Override
//            protected Integer doInBackground(Object... params)
//            {
//                int code = -1;
//                try{
//                    code = LocalUDPDataSender.getInstance(getActivity().getApplication()).sendLoginout();
//                }
//                catch (Exception e){
////                    Log.w(TAG, e);
//                }
//
//                return code;
//            }
//
//            @Override
//            protected void onPostExecute(Integer code)
//            {
//                refreshMyid();
//                if(code == 0)
//                    Log.i("e","注销登陆请求已完成！");
//                else
//                    Toast.makeText(getActivity().getApplication(), "注销登陆请求发送失败。错误码是："+code+"！", Toast.LENGTH_SHORT).show();
//
//            }
//        }.execute();
//    }
    private void refreshMyid() {
//        int myid = ClientCoreSDK.getInstance().getCurrentUserId();


    }


    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        // 入场动画结束后执行  优化,防动画卡顿

        _mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        _mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        hideSoftInput();
    }
}
